package com.angola.sms.base

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.angola.sms.network.NetworkException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

open class BaseViewModel : ViewModel(), IBaseViewModelAction {

    private val mLiveDataLoading = MutableLiveData<Boolean>()
    private val mLiveDataNetworkException = MutableLiveData<NetworkException>()

    open fun eventActionipetrpide(
        showLoadingipetrpide: Boolean = true,
        doingipetrpide: suspend () -> Unit,
        erroripetrpide: suspend (Throwable) -> Unit,
        completedipetrpide: suspend () -> Unit,
    ) {
        if (showLoadingipetrpide) {
            mLiveDataLoading.value = true
        }
        viewModelScope.launch(Dispatchers.IO) {
            try {
                doingipetrpide()
            } catch (e: Exception) {
                erroripetrpide(e)
            } finally {
                completedipetrpide()
            }
        }
    }

    override fun showLoadingipetrpide() {
        mLiveDataLoading.value = true
    }

    override fun dismissLoadingipetrpide() {
        mLiveDataLoading.value = false
    }

    override fun handleNetworkExceptionipetrpide(networkExceptionipetrpide: NetworkException) {
        mLiveDataNetworkException.value = networkExceptionipetrpide
    }

    override fun getLoadingLiveDataipetrpide(): MutableLiveData<Boolean> {
        return mLiveDataLoading
    }

    override fun getNetworkExceptionLiveDataipetrpide(): MutableLiveData<NetworkException> {
        return mLiveDataNetworkException
    }
}